package com.zxs.xss;

import com.zxs.xss.filter.XssFilter;
import com.zxs.xss.util.HtmlFilterKit;
import com.zxs.xss.util.ZxsSafeList;
import jakarta.annotation.Resource;
import jakarta.servlet.DispatcherType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;



@Configuration
@EnableConfigurationProperties({XssProperties.class})
public class XssAutoConfiguration {

	private static final Logger logger = LoggerFactory.getLogger(XssAutoConfiguration.class);
	@Resource
	XssProperties xssProperties;

	@Bean
	@ConditionalOnProperty(prefix = XssProperties.XSS, name = "enable", havingValue = "true")
	public FilterRegistrationBean xssFilterRegistration() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		registration.setDispatcherTypes(DispatcherType.REQUEST);
		registration.setFilter(new XssFilter());
		HtmlFilterKit.safelist=new ZxsSafeList().zxsSafeList(xssProperties.tags);
		registration.addUrlPatterns(xssProperties.getUrlPatterns());
		registration.setName(xssProperties.getName());
		registration.setOrder(xssProperties.getOrder());
		logger.info("XSS filter {} started with URL patterns: {}", xssProperties.getName(), xssProperties.getUrlPatterns());
		return registration;
	}
}
